package com.ajaxlord.confluence.nest;

import com.atlassian.confluence.core.ContentPropertyManager;
import com.atlassian.confluence.renderer.PageContext;
import com.atlassian.confluence.setup.BootstrapManager;
import com.atlassian.renderer.RenderContext;
import com.atlassian.renderer.v2.RenderMode;
import com.atlassian.renderer.v2.macro.BaseMacro;
import com.atlassian.renderer.v2.macro.MacroException;

import java.util.Map;

public class NestExportMacro extends BaseMacro {
    public static final String NEST_KEY = "confluence.nest-export";
    public static final String NEST_KEY_NAME = "name";
    private ContentPropertyManager contentPropertyManager;
    private BootstrapManager bootstrapManager;

    public void setBootstrapManager(BootstrapManager bootstrapManager) {
        this.bootstrapManager = bootstrapManager;
    }

    public void setContentPropertyManager(ContentPropertyManager contentPropertyManager) {
        this.contentPropertyManager = contentPropertyManager;
    }

    public boolean isInline() {
        return true;
    }

    public boolean hasBody() {
        return true;
    }

    public RenderMode getBodyRenderMode() {
        return RenderMode.ALL;
    }

    public String execute(Map parameters, String body, RenderContext renderContext) throws MacroException {
        if (renderContext instanceof PageContext) {
            PageContext pageContext = (PageContext) renderContext;

            String nestKeyName = (String) parameters.get(NEST_KEY_NAME);
            if (nestKeyName == null)
                nestKeyName = "";
            else
                nestKeyName = "." + nestKeyName;
            if (pageContext.getOriginalContext() == pageContext) {
                String contextPath = bootstrapManager.getWebAppContextPath();
                contentPropertyManager.setTextProperty(pageContext.getEntity(), NEST_KEY + nestKeyName, body.trim().replaceAll("href=\'#","href=\'"+contextPath+"/display/"+pageContext.getSpaceKey()+"/"+pageContext.getPageTitle().replaceAll("\\p{Blank}+","+")+"#"));
            }
        }
        return shouldHideNest(parameters) ? "" : body;
    }

    private boolean shouldHideNest(Map parameters) {
        return "true".equalsIgnoreCase((String) parameters.get("hidden"));
    }
}
